// **********WebSocket************* //
let en_js = require('/environment.js');
let user_js = require('/user.js');
let wxp = require('/wxp.js');

const url = en_js.wsUrl; //服务器地址
let socket = null; //SocketTask对象
let sockectInited = false; //SocketTask对象已经初始化
let socketOpen = false; //Socket是否打开
let socketMsgQueue = []; //Socket消息队列
let timeId = null; //计时器id用来重新连接
//socket对象
let webSocket = {
  // 初始化----保证只有一个socket
  init() {
    if (!user_js.getCode()) return;
    if (!sockectInited) {
      this.connectSocket();
    }
  },
  // 创建一个 WebSocket 连接
  connectSocket() {
    // 防止多次初始化
    // 创建并返回SocketTask对象
    socket = wx.connectSocket({
      url: url,
      header: {
        'content-type': 'application/json',
        code: user_js.getCode()
      },
      success: res => {
        if (!sockectInited) {
          sockectInited = true;
        }
        console.log("connectSocket success");
      },
      fail: err => {
        console.log("connectSocket err" + "====" + err);
      }
    });
    // 监听连接打开
    socket.onOpen(res => {
      console.log("socket open");
      socketOpen = true;
      //清空计时器id
      this.clearTimer(timeId);
      // 判断队列里有没有消息，有消息的话发送
      for (let i = 0; i < socketMsgQueue.length; i++) {
        this.sendSocketMessage(socketMsgQueue[i]);
      }
      socketMsgQueue = [];
      // 开始心心跳
      timeId = setInterval(() => {
        this.startHeart();
      }, 5 * 1000);
    });

    // 监听收到消息
    socket.onMessage(res => {
      console.log("socket on message");
      console.log(res);
      this.onSocketMessage(res);
    });

    // 监听连接关闭
    socket.onClose(res => {
      console.log("socket close");
      socketOpen = false;
    });

    // 监听连接错误
    socket.onError(res => {
      console.log("socket error");
      socketOpen = false;
    });
  },

  // reConnect 
  /*
   */
  reConnectSocket() {
    console.log("reConnect socket");
    if (socket) {
      // 可以关闭
      wxp.socketTaskClose(socket).then(res => {
        console.log("关闭上一次socket task成功");
        this.resetDataAndConnectSocket();
      }).catch(err => {
        if (err.errMsg) {
          this.resetDataAndConnectSocket();
        }
        console.log(err);
      });
    }
  },

  //clerAndReConnectSocket
  resetDataAndConnectSocket() {
    socket = null;
    socketMsgQueue = [];
    this.connectSocket();
  },

  //发送消息send
  sendSocketMessage(msg) {
    if (socketOpen) {
      wxp.socketTaskSend(socket, {
        data: msg
      }).then(res => {
        console.log("消息发送成功");
      }).catch(err => {
        console.log("消息发送失败" + '=====' + err);
      });
    } else {
      socketMsgQueue.push(msg);
    }
  },

  // 接收到消息
  onSocketMessage(res) {
    let result = JSON.parse(res.data);
    // 万人团消息
    if (result.type == 'group-no-join') {
      if (this.onSocketMillonMessage) {
        this.onSocketMillonMessage(result);
      }
    }
    //购买提醒
    if (result.type == 'ordered') {
      if (this.onOrderedMessage) {
        this.onOrderedMessage(result);
      }
    }
  },

  //开始心跳
  startHeart() {
    if (!socketOpen) {
      //重新连接
      this.reConnectSocket();
      return;
    }
    // 连接的数据格式
    let sendData = {
      type: "ping",
      result: 1
    }
    let jsaonData = JSON.stringify(sendData);
    //发送数据至服务器
    this.sendSocketMessage(jsaonData);
  },

  // 清空计时器
  clearTimer(timerId) {
    if (timerId) {
      console.log("清理计时器");
      clearInterval(timeId);
      timeId = null;
    }
  }
};

module.exports = {
  webSocket
}